(async function () {
  async function getHeroes() {
    return fetch("https://study.duyiedu.com/api/herolist")
      .then((resp) => resp.json())
      .then((resp) => resp.data.reverse());
  }

  const doms = {
    ul: document.querySelector(".list"),
    types: document.querySelector(".types"),
    input: document.querySelector("input"),
  };

  // 1. 初始化
  const allHeroes = await getHeroes();
  setHeroHTML(allHeroes);

  function setHeroHTML(heroes) {
    doms.ul.innerHTML = heroes
      .map(
        (h) => `<li>
          <a href="https://pvp.qq.com/web201605/herodetail/${h.ename}.shtml" target="_blank">
            <img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/${h.ename}/${h.ename}.jpg"/>
            <span>${h.cname}</span>
          </a>
        </li>`
      )
      .join("");
  }

  // 2。交互事件
  doms.types.addEventListener("click", function (e) {
    if (e.target.classList.contains("radio")) {
      const checkedType = document.querySelector(".checked");
      checkedType && checkedType.classList.remove("checked");
      e.target.classList.add("checked");

      const type = e.target.dataset.type;
      const value = e.target.dataset.value;

      let heroes = allHeroes;
      if (type === "all") {
        heroes = allHeroes;
      } else if (type === "pay_type") {
        heroes = allHeroes.filter((h) => h.pay_type === +value);
      } else if (type === "hero_type") {
        heroes = allHeroes.filter(
          (h) => h.hero_type === +value || h.hero_type2 === +value
        );
      }

      setHeroHTML(heroes);
    }
  });

  doms.input.addEventListener("input", function () {
    const heroes = allHeroes.filter((v) => v.cname.includes(this.value));
    setHeroHTML(heroes);
    document.querySelector(".checked").classList.remove("checked");
    document.querySelector("[data-type=all]").classList.add("checked");
  });
})();
